import { Button } from "antd";
import { FC, ReactElement, useRef, useState } from "react";
import { useAuth } from "../../../api/AuthContext";
import RASEncrypt from "../../../utils/JSEncrypt";
import { NotificationWarn } from "../../common/Notification";
import { Wrap, Mask } from "./UpdateUsername";

interface IProps {}

const UpdatePassword: FC<IProps> = (): ReactElement => {
  const { updatePassword } = useAuth();
  const newPasswordRef = useRef<HTMLInputElement>(null);
  const passwordRef = useRef<HTMLInputElement>(null);
  const [showConfirmInput, setShowConfirmInput] = useState(false);
  const [loading, setLoading] = useState(false);

  const requestUpdatePassword = async () => {
    const password = passwordRef.current?.value;
    const newPassword = newPasswordRef.current?.value;
    if (!password || !newPassword) return;
    if (password === newPassword)
      return NotificationWarn({ message: "新旧密码不能相同" });
    setLoading(true);
    const result = await updatePassword({
      password: RASEncrypt(password),
      newPassword: RASEncrypt(newPassword),
    });
    setLoading(false);
    result && setShowConfirmInput(false);
  };

  return (
    <Wrap>
      <input ref={newPasswordRef} type='password' placeholder='新密码' />
      <Button
        type='primary'
        onClick={() => {
          newPasswordRef.current?.value && setShowConfirmInput(true);
        }}
      >
        确定
      </Button>
      <Mask show={showConfirmInput}>
        <input
          ref={passwordRef}
          type='password'
          placeholder='输入原密码以确定'
        />
        <div>
          <Button
            type='ghost'
            onClick={() => {
              setShowConfirmInput(false);
            }}
          >
            取消
          </Button>

          <Button
            type='primary'
            onClick={requestUpdatePassword}
            loading={loading}
          >
            确定
          </Button>
        </div>
      </Mask>
    </Wrap>
  );
};

export default UpdatePassword;
